package com.example.onion.hxchat.room.repositorywc;

import android.content.Context;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import com.example.onion.hxchat.room.dao.ApplyDao;
import com.example.onion.hxchat.room.dao.UserDao;
import com.example.onion.hxchat.room.entity.Apply;
import com.example.onion.hxchat.room.entity.User;
import com.example.onion.hxchat.room.wcdatabase.MyDataBaseWc;

import java.util.List;

/**
 * @author:onion
 * @data: 2020/7/8
 */
public class ApplyRepository {
    /**
     * Data list from Dao.
     */
    private LiveData<List<Apply>> applys;


    private ApplyDao applyDao;

    public ApplyRepository(Context context,String ownerUserId) {
        //获取数据库实例，数据库采用单例模式
        MyDataBaseWc database = MyDataBaseWc.getInstance(context.getApplicationContext());
        applyDao = database.getApplyDao();
        applys = applyDao.getAllApplyCur(ownerUserId);
    }

    /**
     * Gets all data from Master table from database.
     * @return The list of users
     */
    public LiveData<List<Apply>> getApplys() {
        return applys;
    }

    public void insertMaster(Apply... applys){
        new ApplyRepository.InsertMasterAsyncTask(applyDao).execute(applys);
    }

    //内部类，用于在子线程中访问数据库，如果有多个操作的话，每一个操作都要对应一个AsyncTask
    static class InsertMasterAsyncTask extends AsyncTask<Apply,Void,Void> {

        private ApplyDao applyDao;

        public InsertMasterAsyncTask(ApplyDao applyDao) {
            this.applyDao = applyDao;
        }

        @Override
        protected Void doInBackground(Apply... applys) {
            applyDao.insertApply(applys);
            return null;
        }
    }
}
